package com.zt.location.modules.business;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.zt.location.common.utils.SysCache;
import com.zt.location.modules.base.dao.RealTimeDao;
import com.zt.location.modules.base.dao.TdAlarmDao;
import com.zt.location.modules.base.entity.LimitspeedEntity;
import com.zt.location.modules.base.entity.RealTimeEntity;
import com.zt.location.modules.base.entity.RfidinfoEntity;
import com.zt.location.modules.base.entity.TdAlarmEntity;
import com.zt.location.modules.business.message.TaskData;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ReckonRange {

	private String locationData = null;

	private static final Logger logger = LoggerFactory.getLogger(ReckonRange.class);

	// private List<TaskData> machineDataLst = null;

	private TaskData machineLocantion = null;

	@Autowired
	private TdAlarmDao tdAlarDao;
	
	@Autowired
	private RealTimeDao realTimeDao;

	public String compareRange(String locationData) {
		StringBuilder returnData = new StringBuilder();
		this.locationData = locationData;
		log.info("收到数据包:" + locationData);
		try {
			// 解析数据
			parseLocationData();
			// 1、去除没有移动的手提设备
			RealTimeEntity realTimeEntity = new RealTimeEntity();
			if (setMoveDirection()) {
				// if (!removeMachineNoMove()) {
				realTimeEntity.setReaderId(this.machineLocantion.getReaderID());
				realTimeEntity.setTagCode(this.machineLocantion.getTagCode());
				realTimeEntity.setPos(this.machineLocantion.getTitleNo());
				realTimeEntity.setDirection(this.machineLocantion.getDirection());
				realTimeEntity.setReaderIp(this.machineLocantion.getReaderIP());
				// 2、有变化进行遍历每台手提箱的范围机器是否重合
				List<String> alarmMachine = checkMachinePoint();
				if (null != alarmMachine && alarmMachine.size() > 0) {
					// 添加自己报警
					alarmMachine.add(this.machineLocantion.getReaderIP());
					realTimeEntity.setStatus("2");
					this.machineLocantion.setStatus(2);
				} else {
					realTimeEntity.setStatus("1");
					this.machineLocantion.setStatus(1);
				}

				// 3、将相邻的两台机器调用报警接口
				for (String machineIp : alarmMachine) {
					returnData.append(machineIp).append(",pz|");
					TdAlarmEntity alarmEntity = new TdAlarmEntity();
					alarmEntity.setStatus(0);
					alarmEntity.setIp(machineIp);
					tdAlarDao.save(alarmEntity);
				}
				this.machineLocantion.setAddTime(String.valueOf(System.currentTimeMillis()));
				SysCache.addObject("historeLocationData_" + this.machineLocantion.getReaderID(), locationData);
				// 5、更新缓存
				SysCache.addMachineObject(machineLocantion.getReaderIP(), machineLocantion);
				RealTimeEntity count = realTimeDao.queryObject(realTimeEntity.getReaderId());
				if (null == count) {
					realTimeEntity.setSpeen(0d);
					System.out.println("save:" + realTimeEntity); 
					realTimeDao.save(realTimeEntity);
				} else {
					//判断是否是同一个标签点的位置
					realTimeEntity.setPrePos(count.getPrePos());
					String posLastTime = SysCache.getMaichUpdateTime(this.machineLocantion.getReaderID());
					if(null!=posLastTime){
						String[] temp = posLastTime.split("_");
						if(Integer.parseInt(temp[1])==this.machineLocantion.getTitleNo() && System.currentTimeMillis()-Long.parseLong(temp[0])>=30*1000){
							realTimeEntity.setSpeen(0d);
						}else{
							realTimeEntity.setSpeen(txfloat(0.1,duration(count.getUpdateTime())));	 
						}
						if(Integer.parseInt(temp[1])!=this.machineLocantion.getTitleNo()){
							SysCache.setMaichUpdateTime(this.machineLocantion.getReaderID(), System.currentTimeMillis()+"_"+realTimeEntity.getPos());
							realTimeEntity.setPrePos(count.getPos());
						} 
					}else{
						SysCache.setMaichUpdateTime(this.machineLocantion.getReaderID(), System.currentTimeMillis()+"_"+realTimeEntity.getPos());
						realTimeEntity.setSpeen(0d);
					} 
					
					if(!"2".equals(realTimeEntity.getStatus()) && !"3".equals(realTimeEntity.getStatus())){
						if(checkLimitSpeed(realTimeEntity.getPos(),realTimeEntity.getSpeen(),this.machineLocantion.getCurrentState())){
							alarmMachine.add(this.machineLocantion.getReaderIP());
							realTimeEntity.setStatus("3");
							this.machineLocantion.setStatus(3);
							System.out.println("超速报警");
							returnData.append(this.machineLocantion.getReaderIP()).append(",cs|");
							TdAlarmEntity alarmEntity = new TdAlarmEntity();
							alarmEntity.setStatus(1);
							alarmEntity.setIp(this.machineLocantion.getReaderIP());
							tdAlarDao.save(alarmEntity);
						}
					} 
					realTimeDao.update(realTimeEntity);
					System.out.println("update:" + realTimeEntity);
				} 
				
				// }
				// machineDataLst = null;
				
			}
			
			if (returnData.length() < 1) {
				returnData.append("OK");
			} else {
				returnData.deleteCharAt(returnData.length() - 1);
			}
		} catch (Exception e) {
			log.error("error:" + locationData);
			e.printStackTrace(); 
			returnData.append("OK");
		}
		return returnData.toString();
	}

	private boolean removeMachineNoMove() {
		String historeLocationData = (String) SysCache
				.getObject("historeLocationData_" + this.machineLocantion.getReaderID());
		if (null != historeLocationData) {
			return (this.locationData.equals(historeLocationData));
		} else {
			return false;
		}
	}

	/**
	 * 获得两个时间相差多少分钟
	 * 
	 * @param endTime
	 * @return
	 */
	private double duration(String endTime) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = df.parse(endTime);
			long diff = d1.getTime() - new Date().getTime();// 这样得到的差值是毫秒级别
			
			BigDecimal bi1 = new BigDecimal(Math.abs(diff));
			BigDecimal bi2 = new BigDecimal(3600000);
			BigDecimal divide = bi1.divide(bi2, 6, RoundingMode.HALF_UP);
			double time = divide.doubleValue(); 
			return time;
		} catch (Exception e) {
			return 0;
		}
	}
	
	
	public static double txfloat(double a,double b) { 
		BigDecimal bi1 = new BigDecimal(a);
		BigDecimal bi2 = new BigDecimal(b);
		BigDecimal divide = bi1.divide(bi2, 2, RoundingMode.HALF_UP);
		double speed = divide.doubleValue();
		System.out.println("a=" + a +",b:"+b +",="+speed);
		return speed>40?40:speed; 
	}
	    


	private boolean setMoveDirection() {
		TaskData preMachineLocantion = (TaskData) SysCache.getMachineObject(machineLocantion.getReaderIP());
		// RfidinfoEntity preRfidInfo = null;
		if (null == preMachineLocantion) {
			// preRfidInfo = (RfidinfoEntity) SysCache.getObject("rfid_" +
			// preMachineLocantion.getTagCode());
			this.machineLocantion.setDirection(1);
			return true;
		}
		RfidinfoEntity rfidInfo = (RfidinfoEntity) SysCache.getObject("rfid_" + machineLocantion.getTagCode());
		if (null == rfidInfo) {
			this.machineLocantion.setDirection(1);
			return false;
		}
		// 判断读写器是否与标签方向一致
		log.info("this.machineLocantion.getCurrentState()=" + this.machineLocantion.getCurrentState());
		log.info("rfidInfo.getAxial()=" + rfidInfo.getAxial());
		if ("".equals(this.machineLocantion.getCurrentState())
				|| this.machineLocantion.getCurrentState().equals(rfidInfo.getAxial())) {

			log.info("方向相等................");

			// if (null != rfidInfo) {
			if (preMachineLocantion.getTitleNo() > this.machineLocantion.getTitleNo()) {
				this.machineLocantion.setDirection(2);
			} else if (preMachineLocantion.getTitleNo() < this.machineLocantion.getTitleNo()) {
				this.machineLocantion.setDirection(1);
			} else {
				this.machineLocantion.setDirection(preMachineLocantion.getDirection());
			}
			return true;
			// } else {
			// this.machineLocantion.setDirection(1);
			// return true;
			// }
		} else {// 标签与读写器设备线不一致，丢掉此数据
			return false;
		}
	}

	// 解析json数据
	private void parseLocationData() {
		machineLocantion = JSON.parseObject(this.locationData, TaskData.class);
	}

	// 将对象排序
	/*
	 * private void sortObject() { Collections.sort(machineDataLst, new
	 * Comparator<TaskData>() {
	 * 
	 * @Override public int compare(TaskData o1, TaskData o2) { Collator
	 * collator = Collator.getInstance(Locale.CHINA); return
	 * collator.compare(o1.getTitleStartNo(), o2.getTitleStartNo()); } });
	 * 
	 * }
	 */

	private List<String> checkMachinePoint() {
		List<String> returnData = new ArrayList<String>();
		// machineDataLst = SysCache.getMachineAll();
		for (TaskData temp : SysCache.getMachineAll()) {
			if (!temp.getReaderIP().equals(machineLocantion.getReaderIP())
					&& temp.getCurrentState().equals(machineLocantion.getCurrentState())) {
				if (machineLocantion.getTitleStartNo() <= temp.getTitleNo()
						&& machineLocantion.getTitleEndNo() >= temp.getTitleNo()) {
					returnData.add(temp.getReaderIP());
				}
			}
		}
		return returnData;
	}
	
	private boolean checkLimitSpeed(int pos,Double speed,String axial ){
		LimitspeedEntity limitSpeedEntity = SysCache.getLimitSpeed(pos);
		if(null!=limitSpeedEntity && 0 == limitSpeedEntity.getType() && axial.equals(limitSpeedEntity.getLinename())){
			if(speed>=Double.parseDouble(limitSpeedEntity.getMemo())){
				return true;
			}
		}
		return false; 
	}

}
